package com.clt.web.service.impl;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.clt.web.common.Menu;
import com.clt.web.common.MenuUtil;
import com.clt.web.pojo.WxMenu;
import com.clt.web.service.IWxMenuService;

/**
 * 微信菜单操作的实现类
 * @author wenjian
 *
 */
@Service
@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)
public class WxMenuServiceImpl implements IWxMenuService {

	private final Logger log = LoggerFactory.getLogger(getClass());
	/**
	 * 新建菜单接口
	 * 
	 * 数据格式<br> {
     "button":[
     {	
          "type":"click",
          "name":"今日歌曲",
          "key":"V1001_TODAY_MUSIC"
      },
      {
           "name":"菜单",
           "sub_button":[
           {	
               "type":"view",
               "name":"搜索",
               "url":"http://www.soso.com/"
            },
            {
               "type":"view",
               "name":"视频",
               "url":"http://v.qq.com/"
            },
            {
               "type":"click",
               "name":"赞一下我们",
               "key":"V1001_GOOD"
            }]
       }]
 	}
	 */
	@Override
	public Map<String, Object> synWxMember(HttpServletRequest req) throws Exception{
		Map<String, Object> result = new HashMap<String ,Object>();
		try {
			String basePath = req.getScheme() + "://" + req.getServerName()
					+ ":" + req.getServerPort()+ req.getContextPath();
			//装换菜单配置
			List<WxMenu> wxMenu = new MenuUtil().configToBeans(basePath);
			
			if (wxMenu != null && wxMenu.size() > 0) {
				JSONArray jsonArray = new JSONArray();
				for (WxMenu pMenu : wxMenu) {
					List<WxMenu> childList = pMenu.getChilds();

					JSONObject jsonObject = new JSONObject();
					jsonObject.put("name", pMenu.getName());
					if (childList != null && childList.size() > 0) {
						JSONArray child = getChild(childList);
						jsonObject.put("sub_button", child);
					} else {
						jsonObject.put("type", pMenu.getContentType());
						if ("click".equalsIgnoreCase(pMenu.getContentType())||
								(null!=pMenu.getContentType()&&
//								pMenu.getContentType().startsWith("scancode"))) {
//							//判断出当前菜单微信自带扫一扫功能
								pMenu.getContentType().startsWith("online"))) {
							//判断出当前线上购买
							jsonObject.put("key", pMenu.getContent());
						} else {
							jsonObject.put("url", pMenu.getContent());
						}
					}
					jsonArray.add(jsonObject);
				}

				JSONObject js = new JSONObject();
				js.put("button", jsonArray);
				log.info("用户创建的菜单是 {}:", js);
				// 创建
				Map<String, Object> maps = Menu.createMenu(js.toString());
				if(maps.get("errcode").toString().equals("0")) {
					//成功
					result.put("status",true);
					result.put("msg","");
					log.info("用户创建菜单的结果是 {}:", maps);
				}else {
					result.put("status",false);
					result.put("msg",maps.get("errmsg").toString());
					log.info("用户创建菜单的结果是 {}:", maps);
				}
			}
		} catch (Exception e) {
			result.put("status",false);
			result.put("msg",e.getMessage());
			log.info("用户创建菜单的结果是 {}:", e.getMessage());
		}
		return result;
	}
	
	/**
	 * 获取二级菜单
	 * @param list
	 * @return
	 */
	private JSONArray getChild(List<WxMenu> list) {
		JSONArray jsonArray = new JSONArray();
		if (list != null && list.size() > 0) {
			for (WxMenu pMenu : list) {
				JSONObject jsonObject = new JSONObject();
				jsonObject.put("name", pMenu.getName());
				jsonObject.put("type", pMenu.getContentType());
				if ("click".equalsIgnoreCase(pMenu.getContentType())||
						(null!=pMenu.getContentType()&&
						pMenu.getContentType().startsWith("scancode"))) {
					jsonObject.put("key", pMenu.getContent());
				} else {
					jsonObject.put("url", pMenu.getContent());
				}
				jsonArray.add(jsonObject);
			}
		}
		return jsonArray;
	}

	/**
	 * 微信菜单查询
	 */
	@Override
	public Map<String, Object> findMenuInfo() throws Exception{
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			 map = Menu.getMenuInfo();
		} catch (KeyManagementException e) {
			throw new Exception(e);
		} catch (NoSuchAlgorithmException e) {
			throw new Exception(e);
		} catch (NoSuchProviderException e) {
			throw new Exception(e);
		} catch (InterruptedException e) {
			throw new Exception(e);
		} catch (ExecutionException e) {
			throw new Exception(e);
		} catch (IOException e) {
			throw new Exception(e);
		}
		return map;
	}

}